package bg

import (
	"fmt"
	"math/rand"
	"server/src/global"
	"server/src/model"
	"server/src/server"
	"sort"
	"strconv"
	"time"
)

// 设置全部答案数
func getBgAnsewerNumber() []string {
	// 生成随机数种子
	seed := time.Now().UnixNano()
	source := rand.NewSource(seed)
	generator := rand.New(source)

	// 生成随机数并放入数组中
	const totalNumbers = 20
	const minValue = 1
	const maxValue = 99
	numbers := make([]string, totalNumbers) // 将数字保存为字符串类型的数组
	for i := 0; i < totalNumbers; i++ {
		var number int
		for {
			// 生成随机数并格式化为两位数字符串
			number = generator.Intn(maxValue-minValue+1) + minValue
			// 如果生成的随机数不等于上一个随机数，则跳出循环
			if i == 0 || fmt.Sprintf("%02d", number) != numbers[i-1] {
				break
			}
		}
		numbers[i] = fmt.Sprintf("%02d", number)
	}

	// 对数组进行升序排序
	sort.Strings(numbers)

	return numbers
}

// 分析四个数字从少到多
func analysisNum(answerId int) ([]*model.GuessYaIntegral, error) {
	integrals := []*model.GuessYaIntegral{
		&model.GuessYaIntegral{Num: 1}, &model.GuessYaIntegral{Num: 2},
		&model.GuessYaIntegral{Num: 3}, &model.GuessYaIntegral{Num: 4},
	}
	//获取所有本期数据
	currentAllBetting, err := server.ServerGuess.QueryBgCurrentAllBetting(answerId)
	if err != nil {
		return nil, err
	}
	for _, cabv := range currentAllBetting.BgCurrentBettrings {
		for _, bgnv := range cabv.BgGuessNums {
			switch bgnv.PlayingMethod {
			case global.BG_JIAO:
				bgOod := global.BG_ODDS_JIAO
				integrals[bgnv.Num[0]-1].Integral -= float64(bgOod) * bgnv.Integral
				integrals[bgnv.Num[1]-1].Integral -= float64(bgOod) * bgnv.Integral
			case global.BG_FAN:
				bgOod := global.BG_ODDS_FAN
				integrals[bgnv.Num[0]-1].Integral -= float64(bgOod) * bgnv.Integral
			case global.BG_ZHENG:
				bgOod := global.BG_ODDS_ZHENG
				integrals[bgnv.Num[0]-1].Integral -= float64(bgOod) * bgnv.Integral
				zFang := (bgnv.Num[0] + 2) % 4
				if zFang == 0 {
					zFang = 4
				}
				integrals[zFang-1].Integral -= float64(global.BG_ODDS_BRAW) * bgnv.Integral
			case global.BG_NIAN:
				bgOod := global.BG_ODDS_NIAN
				integrals[bgnv.Num[0]-1].Integral -= float64(bgOod) * bgnv.Integral
				integrals[bgnv.Num[1]-1].Integral -= float64(global.BG_ODDS_BRAW) * bgnv.Integral
			}
		}
	}
	// 设置种子以获取随机性
	rand.Seed(time.Now().UnixNano())

	// 打印原始排序
	fmt.Println("原始排序：")
	printIntegrals(integrals)

	// 如果有相等的 Integral，则打乱排序
	if hasEqualIntegrals(integrals) {
		fmt.Println("存在相等的 Integral，将打乱排序。")
		rand.Shuffle(len(integrals), func(i, j int) {
			integrals[i], integrals[j] = integrals[j], integrals[i]
		})
	}
	// 按照Integral进行从小到大的排序
	sort.Slice(integrals, func(i, j int) bool {
		return integrals[i].Integral < integrals[j].Integral
	})

	return integrals, nil
}

// 全部答案、获取超级数字 和 最终答案
func getAnswer(answerId int, sumIntegral float64) (numbersStr []string, superNum int, answerNum int) {
	// 获取全部答案，并转为为[]int
	isOk := false
	for !isOk {
		integrals, err := analysisNum(answerId)
		if err != nil {
			isOk = false
			continue
		}
		//将str切片转换为int切片
		numbersStr = getBgAnsewerNumber()
		numbersInt := make([]int, len(numbersStr))
		for i, str := range numbersStr {
			num, err := strconv.Atoi(str)
			if err != nil {
				isOk = false
				continue
			}
			numbersInt[i] = num
		}
		//获取胜利概率
		victoryValue := global.BG_PROBABILITY - 1

		//选取超级数字，生成最终答案
		numLen := len(numbersInt)
		superNum = numbersInt[0] + numbersInt[numLen-1]
		for i, j := numLen/2, numLen/2+1; i >= 0 && j < numLen; i, j = i-1, j+1 {
			// i的逻辑
			ziSupnum := numbersInt[i] + superNum
			ziAnswerNum := ziSupnum % 4
			if ziAnswerNum == 0 {
				ziAnswerNum = 4
			}
			if ziAnswerNum == integrals[victoryValue].Num {
				superNum = ziSupnum
				answerNum = ziAnswerNum
				isOk = true
				break
			}
			// j的逻辑
			zjSupnum := numbersInt[j] + superNum
			zjAnswerNum := zjSupnum % 4
			if zjAnswerNum == 0 {
				zjAnswerNum = 4
			}
			if zjAnswerNum == integrals[victoryValue].Num {
				superNum = zjSupnum
				answerNum = zjAnswerNum
				isOk = true
				break
			}
		}
		fmt.Println("____numbersStr____", numbersStr)
		fmt.Println("____superNum____", superNum)
		fmt.Println("____answerNum____", answerNum)
	}
	return
}

func hasEqualIntegrals(integrals []*model.GuessYaIntegral) bool {
	// 使用 map 来存储每个 Integral 出现的次数
	for _, integral := range integrals {
		if integral.Integral < -1.00 || integral.Integral > 1.00 {
			return false
		}
	}
	return true
}

func printIntegrals(integrals []*model.GuessYaIntegral) {
	for _, integral := range integrals {
		fmt.Printf("Num: %d, Integral: %f\n", integral.Num, integral.Integral)
	}
}
